<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div class="energy-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="energyInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" style="margin-bottom: 0;" @queryProcessData="queryProcessData" />
        <div class="energy-detail-content small-padding">
          <div v-for="parent in energyInfoOptions" :key="parent.title" class="content-info">
            <SectionTitle :title="parent.title" font-size="16px" style="margin-bottom: 8px"/>
            <el-form v-loading="infoLoading" :class="{'mobile-el-form': showMobilePage}" label-width="90px" label-position="right">
              <el-row>
                <el-col v-for="item in parent.children" :key="item.value" :span="8" :class="{'info-col':!showMobilePage}" >
                  <el-form-item :label="item.label">
                    <div v-if="item.value === 'createTime'" style="color: #333">
                      {{ energyInfo[item.value] | standardFormatTime('YYYY/MM/DD HH:mm:ss') }}
                    </div>
                    <div v-else-if="item.value !== 'personnelInfo'" style="color: #333">
                      <el-tooltip v-if="energyInfo[item.value] || energyInfo[item.value] === 0" placement="top-start" effect="dark">
                        <div slot="content" style="max-width: 150px;">{{ energyInfo[item.value] }}</div>
                        <div class="ellipsisOne">{{ energyInfo[item.value] }}</div>
                      </el-tooltip>
                      <span v-else>--</span>
                    </div>
                    <div v-else style="height: 32px">
                      <span :style="{color: getFinishedList.length && getFinishedList.length === getTotalNum ? '#333' : '#FF4E5F'}">{{ getFinishedList.length }}</span> / {{ getTotalNum }}
                      <span class="view-user-btn" @click="showUserInfoDialog">查看人员<i class="el-icon-arrow-right"/></span>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col v-if="parent.title === '基本信息'" :span="24">
                  <el-form-item label="备注:">
                    <ToolTip :content="energyInfo.remark"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div :class="{'scroll-table':showMobilePage}" class="content-table">
            <div class="content-table-title">
              <SectionTitle title="精力分配表" font-size="16px"/>
              <template v-if="showMobilePage && stepActiveId !== PROGRESS_STEP.FINISHED && editTableEventOpen">
                <el-button v-if="addEditPermission" class="empty-btn-style" size="small" plain @click="handleEdit(0)">添加编辑</el-button>
                <el-button v-if="hasRouteAuth('energy:energyEdit:all') || hasRouteAuth('energy:department:edit')" size="small" @click="handleEdit(1)">编辑全部</el-button>
              </template>
            </div>
            <div :class="{'mobile-filter': showMobilePage}" style="position:relative; margin-bottom:16px;">
              <FilterInput
                v-model="filterInput"
                :show-mobile-icon="showMobilePage"
                :filter-list="filterList"
                show-search-btn
                class="FilterTool"
                @handelClick="queryDetailList"
                @queryEmpty="queryEmpty"/>
              <div :style="showMobilePage?'flex:1;':''" class="search-right-checkbox">
                <el-checkbox v-model="onlyShowMe" style="margin-right: 20px;" @change="queryDetailList(true)" >只看我</el-checkbox>
              </div>
              <div class="table-top-opeator-bar">
                <template v-if="!showMobilePage && stepActiveId !== PROGRESS_STEP.FINISHED && editTableEventOpen">
                  <el-button v-if="addEditPermission" class="empty-btn-style" size="small" plain @click="handleEdit(0)">添加编辑</el-button>
                  <el-button v-if="hasRouteAuth('energy:energyEdit:all') || hasRouteAuth('energy:department:edit')" size="small" @click="handleEdit(1)">编辑全部</el-button>
                </template>
                <btnGroup
                  v-if="showBtnGroup"
                  ref="btnGroupRef"
                  :list="[
                    {label:'导入', importApi:'/admin/energy/detail/list/import', extendParams:{ effortAllocationId: energyId }, callback: importCallback, type: 'import', auth: editTableEventOpen && hasRouteAuth('energy:energyList:import') },
                    {label:'导出', exportApi:'/admin/energy/detail/list/export', exportName:'精力分配表', beforeExport: exportBeforeExport, type: 'export', auth: hasRouteAuth('energy:energyList:export')}
                  ]"
                  style="margin-left: 16px;"
                />
              </div>
            </div>
            <div class="table-list">
              <DetailTable
                ref="detailTableRef"
                :list-loading="listLoading"
                :list-data="listData"
                :is-empty-table="isEmptyTable"
                @sortMethod="sortMethod"
                @showUserInfoDialog="showUserInfoDialog"
              />
              <el-pagination
                v-if="showMobilePage && listData.total"
                :current-page="listData.page"
                :page-size="listData.perPage"
                :total="listData.total"
                :small="true"
                :page-sizes="[20, 50, 100, 250, 500]"
                style="margin: 10px 0"
                layout="total, prev, next, jumper"
                @size-change="pageSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :process-id="processId"
          :main-id="energyId"
          :version="version"
          :get-comments-api="getEnergyComments"
          :comment-add-api="energyCommentAdd"
          :process-revocation-api="energyProcessRevocation"
          :process-recall-api="energyProcessRecall"
          :process-audit-api="energyProcessAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.ENERGY"
          :process-type="PROCESS_TYPE.ENERGY"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[proposer]"
          :approval-module-type="APPROVAL_MODULE_TYPE.ENERGY"
          :is-apply="isApply"
          next-approve-module-id="energyId"
          redirect-url="/operate/energy/detail"
          detail-page-router-name="energyDetail"
          edit-page-router-name="energyEdit"
          @toBack="toBack"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handlePressSend="handlePressSend"
          @handleCancelPress="handleCancelPress"
          @handleCreateNew="handleCreateNew('energyEdit',{},{energyId: energyId,reapplyId: processId})"
          @handleModify="handleModify('energyEdit',{},{energyId: energyId,remodifyId: processId})"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
        >
          <div slot="pager" class="pagination-pager" style="height: 56px; display: flex;margin-right: 20px;">
            <el-pagination
              v-if="!showMobilePage"
              slot="pager"
              :current-page="listData.page"
              :page-size="listData.perPage"
              :total="listData.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="pageSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </ExamineAndApprove>
      </template>
      <DeniedPlaceholder v-else />
      <UserInfoDialog
        ref="userInfoDialogRef"
        :process-status="stepActiveId"
        :energy-id="energyId"
        :show-mobile-page="showMobilePage"
        :unfilled-list="getUnfilledList"
        :finished-list="getFinishedList"
      />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/operate/energy/detail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
    </div>
  </div>
</template>

<script>
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import SectionTitle from '@/components/Title';
import DetailTable from '../components/detailTable';
import UserInfoDialog from '../components/userInfoDialog';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import Explanation from '@/components/Common/explanation';
import {
  energyInfo,
  energyDetailList,
  getEnergyComments,
  energyCommentAdd,
  getAddEditPermission,
  energyProcessRevocation,
  energyProcessRecall,
  energyProcessAudit,
  getEnergyTypeList
} from '@/api/energy';
import { platformList } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { standardFormatTime } from '@/filters/date';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { PER_PAGE, APPROVAL_MODULE_TYPE } from '@/utils/const';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { mapState } from 'vuex';
import schedule from '@/mixins/schedule';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';

export default {
  name: 'EnergyDetail',
  filters: {
    standardFormatTime
  },
  components: {
    ProgressStep,
    SectionTitle,
    UserInfoDialog,
    btnGroup,
    Explanation,
    DetailTable,
    ExamineAndApprove
  },
  mixins: [schedule],
  data() {
    return {
      BUSINESS_TYPE,
      PROGRESS_STEP,
      PROCESS_TYPE,
      getEnergyComments,
      energyCommentAdd,
      energyProcessRevocation,
      energyProcessRecall,
      energyProcessAudit,
      APPROVAL_MODULE_TYPE,
      stepActiveId: PROGRESS_STEP.PENDING,
      permissionDenied: false, // 详情页是否可查看
      listData: { items: [] },
      infoLoading: false,
      listLoading: false,
      onlyShowMe: false,
      addEditPermission: false,
      editTableEventOpen: false, // 当前审批节点开启表单编辑事件
      isEmptyTable: false, // 分配列表是否为空，判断空样式
      filterInput: {},
      sortRules: '',
      perPage: PER_PAGE,
      curPage: 1,
      energyId: '', // 审批单号id
      processId: '', // 审批进程id
      energyInfo: {}, // 精力详情基本信息
      platformOption: [], // 下单平台
      deptTreeList: [], // 所属经营体
      energyTypeOption: [],
      rangeKeyArr: [
        { attr: 'entryTime', start: 'entryStartTime', end: 'entryEndTime', type: 'round' },
        { attr: 'dimissionTime', start: 'dimissionStartTime', end: 'dimissionEndTime', type: 'round' },
        { attr: 'transferTime', start: 'transferStartTime', end: 'transferEndTime', type: 'round' },
        { attr: 'updateTime', start: 'updateStartTime', end: 'updateEndTime', type: 'round' }
      ]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    getUnfilledList() {
      const { personnelInfo } = this.energyInfo;
      return personnelInfo && personnelInfo['unfilledList'] || [];
    },
    getTotalNum() {
      const { personnelInfo } = this.energyInfo;
      return personnelInfo && personnelInfo['totalNum'] || 0;
    },
    getFinishedList() {
      const { personnelInfo } = this.energyInfo;
      return personnelInfo && personnelInfo['finishedList'] || [];
    },
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    filterList() {
      return [
        { keyword: 'resourceName', name: '账号/项目名称', type: 'input', labelWidth: '100px' },
        { keyword: 'userName', name: '运营人员', type: 'input', labelWidth: '100px' },
        { keyword: 'remark', name: '备注', type: 'input', labelWidth: '100px' },
        { keyword: 'updater', name: '更新人', type: 'input', labelWidth: '100px' },
        { keyword: 'entryTime', labelWidth: '100px', name: '入职时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'dimissionTime', labelWidth: '100px', name: '离职时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'transferTime', labelWidth: '100px', name: '调岗时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'updateTime', labelWidth: '100px', name: '更新时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.platformOption },
        { keyword: 'attributionMatrix', name: '所属经营体', type: 'cascaderSelect', valueName: 'name', childrenVal: 'children', strictly: false, options: this.deptTreeList },
        { keyword: 'energyTypeId', name: '精力类型', type: 'select', options: this.energyTypeOption }
      ];
    },
    energyInfoOptions() {
      return [
        {
          title: '创建信息',
          children: [
            { label: '申请人:', value: 'proposer' },
            { label: '申请人部门:', value: 'proposerDepartmentName' },
            { label: '创建人:', value: 'creatorName' },
            { label: '创建人部门:', value: 'departmentName' },
            { label: '创建时间:', value: 'createTime' }
          ]
        },
        {
          title: '基本信息',
          children: [
            { label: '月份:', value: 'month' },
            { label: '填写人数:', value: 'personnelInfo' },
            { label: '账号数量:', value: 'accountNum' }
          ]
        }
      ];
    },
    isCreate() { // 创建人
      return this.userInfo.id === this.energyInfo.creatorId;
    },
    showBtnGroup() {
      // 待提交状态默认展示导入，不作权限判断
      return this.stepActiveId === PROGRESS_STEP.PENDING || hasRouteAuth('energy:energyList:export') || hasRouteAuth('energy:energyList:import');
    },
    createUser() {
      let user = { id: this.energyInfo.creatorId, userName: this.energyInfo.creatorName };
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    },
    proposer() {
      let user = { id: this.energyInfo.proposerId, userName: this.energyInfo.proposer };
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    },
    isApply() { // 申请人
      const proposerId = this.energyInfo && this.energyInfo.proposerId ? this.energyInfo.proposerId : '';
      return proposerId && this.userInfo.id === proposerId;
    }
  },
  created() {
    this.initData();
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryPlatformList(); // 下单平台
      this.queryDeptTreeList(); // 所属经营体
      this.getAddEditPermission(); // 是否可编辑
      this.queryProcessData(); // 流程数据
      this.queryDetailList(true, true);
      this.getEnergyTypeList(); // 下单平台
    },
    initRouteData() {
      this.energyId = this.$route.query.energyId;
      this.processId = this.$route.query.processId;
      if (!this.energyId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    // 获取基本信息
    queryEnergyInfo() {
      this.infoLoading = true;
      energyInfo(this.energyId).then(res => {
        this.infoLoading = false;
        if (res.code === 200) {
          this.handleProcessCheck(res.data.processId);
          this.energyInfo = res.data;
          if (res.data.processStatus === 3) { // 3为撤销
            this.stepActiveId = PROGRESS_STEP.PENDING;
          } else {
            this.stepActiveId = res.data.processStatus;
          }
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.infoLoading = false;
      });
    },
    getAddEditPermission() {
      getAddEditPermission(this.energyId).then(res => {
        if (res.code === 200) {
          this.addEditPermission = res.data && res.data.hasPermission;
          this.editTableEventOpen = res.data && res.data.editTableEventOpen;
        }
      });
    },
    async queryPlatformList() {
      try {
        const result = await platformList();
        result.data.forEach(item => {
          item.label = item.value;
          item.value = item.id;
        });
        this.platformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    async getEnergyTypeList() {
      try {
        const result = await getEnergyTypeList();
        result.data.forEach(item => {
          item.label = item.energyType;
          item.value = item.id;
        });
        this.energyTypeOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(_ => {});
    },
    queryProcessData() {
      this.queryEnergyInfo();
      this.getAuditSchedule();
      this.getAddEditPermission();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    pageSizeChange(num) {
      this.perPage = num;
      this.queryDetailList(true);
    },
    handleCurrentChange(num) {
      this.curPage = num;
      this.queryDetailList();
    },
    sortMethod(sortRules) {
      this.sortRules = sortRules;
      this.queryDetailList();
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      params.onlyShowMe = this.onlyShowMe;
      params.page = this.curPage;
      params.perPage = this.perPage;
      params.id = this.energyId;
      params.sortRules = this.sortRules;
      paramsRangeFormat(this.rangeKeyArr, params);
      return params;
    },
    queryDetailList(reset = false, isInit = false) {
      this.listLoading = true;
      reset && (this.curPage = 1);
      const params = this.formatParams();
      energyDetailList(params).then(res => {
        if (res.code === 200) {
          this.listData = res.data;
          if (isInit && !res.data.items.length) {
            this.isEmptyTable = true;
          }
        }
        this.listLoading = false;
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    // 导出
    exportBeforeExport() {
      const params = this.formatParams();
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    },
    importCallback() {
      this.queryDetailList(true);
    },
    queryEmpty() {
      this.$refs['detailTableRef'].resetTable();
      this.sortRules = '';
      this.onlyShowMe = false;
      this.filterInput = {};
      this.queryDetailList(true);
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'energy' });
      }
    },
    showUserInfoDialog() {
      this.$refs['userInfoDialogRef'].dialogVisible = true;
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    // 编辑
    handleEdit(editAll = 0) {
      this.$router.push({
        name: 'energyDetailEdit',
        query: {
          editAll,
          energyId: this.energyId,
          processId: this.processId
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
.content-info {
  margin-bottom: 24px;
}
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  &:hover {
    background: #406EFF;
    color: #fff;
  }
}
.energy-detail-container {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 56px);
  .energy-detail-content {
    padding: 16px 24px 0;
    .info-col {
      border-right: 1px solid #EBEEFD;
      padding-left: 20px !important;
    }
    .view-user-btn {
      margin-left: 8px;
      line-height: 32px;
      color: #406EFF;
      cursor: pointer;
    }
    .info-col:nth-child(3n) {
      border-right: none;
    }
    .info-col:nth-child(3n + 1) {
      padding-left: 0 !important;
    }
  }
    &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .scroll-table {
    width: 100%;
    overflow-x: scroll;
  }
  .content-table {
    .content-table-title {
      margin-bottom: 16px;
      display: flex;
      align-items: center;
    }
    .search-right-checkbox {
      position: absolute;
      left: 488px;
      top: 6px;
      display:flex;
      align-items:center;
    }
    .table-top-opeator-bar {
      ::v-deep .el-button {
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    .table-list {
      border-radius: 10px;
      .el-row {
        padding: 0;
      }
    }
  }
}
.btns-container {
  margin-top: 20px;
}
::v-deep .el-pagination {
  padding: 0 !important;
  display: flex;
  align-items: center;
}
.pagination-pager {
  height: 100%;
  display: flex;
  align-items: center;
  ::v-deep .el-pagination__jump {
    display: flex;
    align-items: center;
  }
  ::v-deep .el-input {
    margin: 0;
    width: 80px;
  }
  ::v-deep .el-input--suffix {
    ::v-deep .el-input__inner {
      border: none;
      padding-left: 0;
      padding-right: 20px;
    }
  }
  ::v-deep .el-pagination__editor {
    ::v-deep .el-input__inner {
      width: 40px;
    }
  }
  ::v-deep .el-pagination__jump {
    ::v-deep .el-input {
      width: 50px;
    }
  }
  ::v-deep .el-pagination__total {
    // border-left: 1px solid #ddd;
    height: 20px;
    display: inline-block;
    line-height: 20px;
    padding-left: 5px;
  }
  ::v-deep .el-pagination__sizes {
    margin-right: 0;
  }
}
.mobile-filter {
  display: flex;
  align-items: center;
  .search-right-checkbox,.table-top-opeator-bar {
    position: relative !important;
    left: auto !important;
    top: auto !important;
  }
}
</style>
